import json
import os
import re
import subprocess


def read_json(filename, file_path=None, abs_path=False):
    if abs_path:
        path = filename
    else:
        path = file_path + os.sep + filename
    with open(path, "r", encoding='utf-8') as f:
        data = json.load(f)
    return data


def write_json(data_dict, filename='ext.json', file_path=None, abs_path=False):
    json_str = json.dumps(data_dict, indent=2, ensure_ascii=False)
    if abs_path:
        path = filename
    else:
        path = file_path + os.sep + filename
    with open(path, 'w', encoding='utf-8') as json_file:
        json_file.write(json_str)


def read_js(filename, file_path=None, abs_path=False):
    if abs_path:
        path = filename
    else:
        path = file_path + os.sep + filename
    with open(path, "r", encoding='utf-8') as f:
        data = f.readlines()
    return data


def write_js(data_str, filename, file_path=None, abs_path=False):
    if abs_path:
        path = filename
    else:
        path = file_path + os.sep + filename
    with open(path, "w", encoding='utf-8') as file:
        file.write(f"{data_str}")


class ChangeConfig:

    def __init__(self, pro_path):
        self.pro_path = pro_path

    def change_ext_json(self, exitid):
        data = read_json("ext.json", self.pro_path)
        print(data)
        if not data["extEnable"]:
            data["extEnable"] = True
        data["extAppid"] = exitid
        data['ext']["extAppid"] = exitid
        write_json(data, "ext.json", file_path=self.pro_path)

    def change_app_js(self, envVersion):
        js_raw = read_js('app.js', self.pro_path)
        for line in js_raw:
            if "envVersion: '" in line:
                new_line = re.sub("envVersion: '(.*?)'", f"envVersion: '{envVersion}'", line)
                index = js_raw.index(line)
                js_raw[index] = new_line
        data_str = ''.join(js_raw)
        write_js(data_str, 'app.js', self.pro_path)

    def change_config_js(self, env):
        js_raw = read_js('config.js', self.pro_path + os.sep + 'utils')
        for line in js_raw:
            if "const env = '" in line:
                new_line = re.sub("const env = '(.*?)'", f"const env = '{env}'", line)
                index = js_raw.index(line)
                js_raw[index] = new_line
        data_str = ''.join(js_raw)
        write_js(data_str, 'config.js', self.pro_path + os.sep + 'utils')

    def change_api_base_config_js(self, env):
        js_raw = read_js('config.js', self.pro_path + os.sep + 'api' + os.sep + 'base')
        for line in js_raw:
            if "const env = '" in line:
                new_line = re.sub("const env = '(.*?)'", f"const env = '{env}'", line)
                index = js_raw.index(line)
                js_raw[index] = new_line
        data_str = ''.join(js_raw)
        write_js(data_str, 'config.js', self.pro_path + os.sep + 'api' + os.sep + 'base')


class InstallPnpm:

    def __init__(self, pro_path):
        print("需要安装 Node.js v16.14以上版本")
        print("需要安装 pnpm")
        self.pro_path = pro_path

    def install(self):
        print(f"{self.pro_path[:2]}")
        os.system(f"{self.pro_path[:2]} && cd {self.pro_path} && pnpm i && cd packageMangHeIm && chdir && pnpm install")


class OpenPro:
    def __init__(self, pro_path, tool_path=None):
        print("需要设置开发者工具环境变量，或指定路径，才可使用自动加载功能")
        self.pro_path = pro_path
        self.tool_path = tool_path

    def open_pro(self):
        if self.tool_path:
            out = subprocess.check_output(f"{self.tool_path[:2]} && cd {self.tool_path} && cli -o {self.pro_path}",shell=True)
        else:
            out = subprocess.check_output(f"cli -o {self.pro_path}", shell=True)
        print(out)


class GitCheck:
    def __init__(self, pro_path):
        self.pro_path = pro_path

    def git_force_fetch(self, branch):
        out = subprocess.check_output(
            f"{self.pro_path[:2]} && cd {self.pro_path} && git fetch --all && git reset --hard origin/{branch} && git pull",shell=True)
        print(out)

    def git_change_branch(self, branch, newbranch):
        self.git_force_fetch(branch)
        out = subprocess.check_output(f"{self.pro_path[:2]} && cd {self.pro_path} && git checkout {newbranch}",shell=True)
        print(out)
        self.git_force_fetch(newbranch)

    def git_get_current_branch(self):
        out = subprocess.check_output(f"{self.pro_path[:2]} && cd {self.pro_path} && git branch",shell=True)
        print(str(out))


if __name__ == '__main__':
    # cc = ChangeConfig("F:\im-xcx")
    # cc.change_ext_json('wxf304b2b1daaae783')
    # cc.change_app_js("develop")
    # cc.change_config_js('test')
    # cc.change_api_base_config_js('test')
    ii = InstallPnpm("F:\im-xcx")
    ii.install()
    # oo = OpenPro("F:\im-xcx", 'D:\微信web开发者工具')
    # oo.open_pro()
    # gg = GitCheck("F:\im-xcx")
    # gg.git_force_fetch("master")
    # gg.git_change_branch("master", "master-online")
    # gg.git_get_current_branch()